package com.v1.video.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.v1.video.R;
import com.v1.video.domain.BaseInfo;
import com.v1.video.domain.LoginInfo;
import com.v1.video.engine.NetEngine;

public class SetUserNameActivity extends BaseActivity implements OnClickListener {

	private EditText edit_userName;
	private EditText edit_nickName;
	private EditText edit_pwd;
	private final String TAG = "SetUserNameActivity";
	
	private String phoneNum;
	private String userId;
	
	private ProgressDialog progDialog;
	private TextView txtTitle = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_login_register3);
        
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.iv_result:
			onBackPressed();
			break;
		case R.id.iv_personal_headimg:
//			showPicDialog();
			break;
		case R.id.button_save:
		    try{
    			if(edit_userName.getText().toString().equals("")){
    				
    				Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
    				return;
    				
    			}
    			if(edit_nickName.getText().toString().equals("")){
    				
    				Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
    				return;
    				
    			}
    			if(edit_pwd.getText().toString().equals("")){
    				
    				Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
    				return;
    				
    			}
    			String userName = edit_userName.getText().toString();
    			if(userName.equals("")){
                    Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    byte name[] = userName.getBytes("GBK");
                    if(name != null){
                        if(name.length < 4 || name.length > 20){
                            Toast.makeText(this, "用户名长度只能在4-20位数字和字符", Toast.LENGTH_SHORT).show();
                            return; 
                        }
                    }else{
                        Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                        return; 
                    }
                }            
                Pattern p = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]+$");
                Matcher m = p.matcher(userName);
                boolean b = m.matches();
                if (!b) {
                    Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
    			{
    				String nameStr = edit_nickName.getText().toString();
	    			if(nameStr.equals("")){
	                    Toast.makeText(this, "昵称格式错误", Toast.LENGTH_SHORT).show();
	                    return;
	                }else{
	                    byte name[] = nameStr.getBytes("GBK");
	                    if(name != null){
	                        if(name.length < 4 || name.length > 20){
	                            Toast.makeText(this, "昵称长度只能在4-20位数字和字符", Toast.LENGTH_SHORT).show();
	                            return; 
	                        }
	                    }else{
	                        Toast.makeText(this, "昵称格式错误", Toast.LENGTH_SHORT).show();
	                        return; 
	                    }
	                }            
	                Pattern p1 = Pattern.compile("^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$");
	                Matcher m1 = p1.matcher(nameStr);
	                boolean b1 = m1.matches();
	                if (!b1) {
	                    Toast.makeText(this, "昵称格式错误", Toast.LENGTH_SHORT).show();
	                    return;
	                }
                }
    //			Pattern p = Pattern.compile("[_a-zA-Z][_a-zA-Z0-9]");
    //			Matcher m = p.matcher(nameStr);
    //			boolean b = m.matches();
    //			if(nameStr.length() < 4 ||
    //					nameStr.length() > 16||
    //					b
    //					){
    //				Toast.makeText(this, "用户名格式错误", Toast.LENGTH_SHORT).show();
    //				return;
    //			}
    			String nameStr2 = edit_pwd.getText().toString();
    			Pattern p2 = Pattern.compile("[_a-zA-Z][_a-zA-Z0-9]");
    			Matcher m2 = p2.matcher(nameStr2);
    			boolean b2 = m2.matches();
    			if(nameStr2.length() < 6 ||
    					nameStr2.length() > 20||
    					b2
    					){
    				Toast.makeText(this, "密码格式错误", Toast.LENGTH_SHORT).show();
    				return;
    			}
    			
//    			Logger.i(TAG, "LoginInfo.getInstance().getBangdinglist().size()="+LoginInfo.getInstance().getBangdinglist().size());
    			if(LoginInfo.getInstance().getBangdinglist() != null){
    			    if(LoginInfo.getInstance().getBangdinglist().size() > 0){
    			        progDialog = ProgressDialog.show(this, null,"请稍候", true, false);
    			        sendUserName(LoginInfo.getInstance().getUserId(), LoginInfo.getInstance().getBangdinglist().get(0).getType(), 
    			        		edit_userName.getText().toString(), edit_pwd.getText().toString(),edit_nickName.getText().toString());
    			    }else{
    			        Toast.makeText(SetUserNameActivity.this, "授权异常，请重新授权！", Toast.LENGTH_SHORT).show();
    			        finish();
    			    }
    			}else{
    			    Toast.makeText(SetUserNameActivity.this, "授权异常，请重新授权！", Toast.LENGTH_SHORT).show();
    			    finish();
    			}
    			
    			
		    }catch(Exception e){
		        if(progDialog != null)
	            {
	                progDialog.dismiss();
	            }
	            progDialog = null;
		        e.printStackTrace();
		    }
			break;
		}
	}
	
	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		edit_userName = (EditText)findViewById(R.id.editText_username);
		edit_nickName = (EditText)findViewById(R.id.editText_nickname);
		edit_pwd = (EditText)findViewById(R.id.editText_password);
		findViewById(R.id.ll_thirdpart_content).setVisibility(View.INVISIBLE);
		txtTitle = (TextView)findViewById(R.id.tv_title);
        
		if(LoginInfo.getInstance().getLoginState() == LoginInfo.THIRDPARTY_LOGIN){
			findViewById(R.id.iv_personal_headimg).setVisibility(View.GONE);
		}
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		txtTitle.setText(R.string.option_username_modify);
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                onBackPressed();
            }
        });
		findViewById(R.id.button_save).setOnClickListener(this);
	}

	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			if(msg.what == 0){
				
				BaseInfo result = (BaseInfo)(msg.obj);
				
				if(result != null){
					if(result.getCode().equals("1")){
						Toast.makeText(SetUserNameActivity.this, "用户名及密码设置成功", Toast.LENGTH_SHORT).show();
						LoginInfo.getInstance().setUserName(edit_userName.getText().toString());
						LoginInfo.getInstance().setLoginName(edit_userName.getText().toString());
						LoginInfo.getInstance().setLoginPw(edit_pwd.getText().toString());
						LoginInfo.getInstance().setNickName(edit_nickName.getText().toString());
						LoginInfo.getInstance().setLoginState(LoginInfo.LOGIN);
						LoginInfo.getInstance().setSetUserName(true);
						LoginInfo.getInstance().saveInstance(SetUserNameActivity.this);
						if(progDialog != null)
						{
						    progDialog.dismiss();
						}
						progDialog = null;
						finish();
						return;
					}else if(result.getCode().equals("7")){
					    if(progDialog != null)
                        {
                            progDialog.dismiss();
                        }
                        progDialog = null;
                        LoginInfo.getInstance().setLoginState(LoginInfo.LOGIN);
                        LoginInfo.getInstance().setSetUserName(true);
                        LoginInfo.getInstance().saveInstance(SetUserNameActivity.this);
                        Toast.makeText(SetUserNameActivity.this, "亲，用户名已经设置过了！", Toast.LENGTH_SHORT).show();
                        finish();                        
					}
					else{
						Toast.makeText(SetUserNameActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
				else{
					Toast.makeText(SetUserNameActivity.this, "用户名及密码设置失败", Toast.LENGTH_SHORT).show();
				}
				
			}else if(msg.what == 1){
			    Toast.makeText(SetUserNameActivity.this, "用户名及密码设置失败,请稍后再试！", Toast.LENGTH_SHORT).show();
			}
			if(progDialog != null)
            {
                progDialog.dismiss();
            }
			progDialog = null;
		}
		
	};
	
	private void sendUserName(final String userId, final String logintype, final String username, final String pwd,final String nickName){
		
		new Thread(){
			
			public void run(){
				
				try {
//				    Logger.i(TAG, "sendUserName方法执行了，调用的是NetEngine().updateUserBySSO这个方法");
					BaseInfo baseInfo = new NetEngine().updateUserBySSO(userId, logintype, username, pwd,nickName);
					Message msg = new Message();
					msg.what = 0;
					msg.obj = baseInfo;
					handler.sendMessage(msg);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
				} 				
			}
			
		}.start();
		
	}
	
}
